package com.cy.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.server.dto.RoleDto;
import com.cy.server.pojo.Menu;
import com.cy.server.pojo.MenuRole;
import com.cy.server.pojo.RespBean;
import com.cy.server.pojo.Role;
import com.cy.server.service.IMenuRoleService;
import com.cy.server.service.IMenuService;
import com.cy.server.service.IRoleService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @peoject: yeb
 * @description: 权限组
 * @author: LiShaoZhuo
 * @create: 2021-04-29 15:26
 **/
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    IRoleService roleService;
    @Autowired
    IMenuService menuService;
    @Autowired
    IMenuRoleService menuRoleService;

    @ApiOperation("查询所有角色信息")
    @PostMapping("/list")
    public RespBean getAllRoles(@RequestBody RoleDto roleDto){
        PageInfo<Role> pageInfo = roleService.selectRole(roleDto);
        return RespBean.success(pageInfo);
    }

    @ApiOperation("添加角色信息")
    @PostMapping("/add")
    public RespBean addRole(@RequestBody Role role){
        if (!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)){
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation("删除角色信息")
    @DeleteMapping("/delete/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid){
        if (roleService.removeById(rid)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation("查询所有菜单信息")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation("根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid))
                .stream()
                .map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation("更新角色菜单")
    @PutMapping("/update")
    public RespBean updateMenuRole(Integer rid, Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
